package com.aitoedu.server.controller;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/user/talk")
public class WebSocketController {

    private static ConcurrentHashMap<Long, WebSocketController> clients = new ConcurrentHashMap<>();

    private Session session;

    private Long userId;

    @Autowired
    private RedisTemplate redisTemplate;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        this.userId = Long.valueOf((String) StpUtil.getLoginId());
        clients.put(userId, this);
    }

    @OnMessage
    public void onMessage(Session session,String message){
        Long id = Long.valueOf(message.split(",")[0]);
        String msg = message.split(",")[1];
        try {
            if(clients.get(id) != null) {
                clients.get(id).session.getBasicRemote().sendText(msg);
            }else {
                redisTemplate.opsForValue().set("receive:"+id, this.userId+","+msg);
            }
        }catch (IOException e){
            log.error("发送异常：{}", e.getStackTrace());
        }
    }

    @OnClose
    public void onClose(){
        clients.remove(this.userId);
    }

    @OnError
    public void onError(Session session, Throwable error){
        log.error("发生错误");
        error.printStackTrace();
    }
}
